/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.toggletest;

import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ToggleTableModel extends AbstractTableModel {
    List<ToggleRow> toggles = new ArrayList<ToggleRow>();

    public ToggleTableModel(List<ToggleRow> currentList) {
        setToggles(currentList);
    }

    public int getRowCount() {
        return toggles.size() + 1;
    }

    public int getColumnCount() {
        return 2;
    }

    public Class getColumnClass(int col) {
        return String.class;
    }

    public Object getValueAt(int row, int col) {
        if (row == toggles.size()) {
            return "";
        }
        ToggleRow toggle = this.toggles.get(row);
        return col == 0 ? toggle.getFrom() : toggle.getTo();
    }

    public boolean isCellEditable(int row, int col) {
        return true;
    }

    public void setValueAt(Object value, int row, int col) {
        String text = (String) value;
        if (row == toggles.size()) {
            toggles.add(row, new ToggleRow("", ""));
//            addRow(row);
        }
        ToggleRow toggle = this.toggles.get(row);
        if (col == 0) {
            toggle.setFrom(text);
        } else {
            toggle.setTo(text);
        }
        fireTableCellUpdated(row, col);
    }

    public void addRow(int row) {
        if (row >= 0 && row < toggles.size()) {
            toggles.add(row, new ToggleRow("", ""));
            fireTableRowsInserted(row, row);
        }
    }

    public Iterator iterator() {
        return toggles.iterator();
    }

    public void removeRow(int selectedRow) {
        if (selectedRow >= 0 && selectedRow < toggles.size()) {
            toggles.remove(selectedRow);
            fireTableRowsDeleted(selectedRow, selectedRow);
        }
    }

    public List<ToggleRow> getToggles() {
        return toggles;
    }

    public void setToggles(List<ToggleRow> newToggles) {
        toggles.clear();
        toggles.addAll(newToggles);
        fireTableDataChanged();
    }
}
